<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-overlay"></div>
    </div>
    
    <div class="login-box">
      <div class="login-header">
        <div class="login-logo">
          <div class="logo-icon">🏦</div>
          <h1>金融监控系统</h1>
        </div>
        <p class="login-subtitle">Financial Monitoring System</p>
      </div>

      <el-form class="login-form" @submit.prevent="handleSubmit">
        <el-alert 
          v-if="error" 
          :title="error" 
          type="error" 
          :closable="false" 
          show-icon
          class="login-error-alert"
        />

        <el-form-item label="用户名">
          <el-input
            v-model="username"
            placeholder="请输入用户名"
            :disabled="loading"
            autocomplete="username"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item label="密码">
          <el-input
            v-model="password"
            type="password"
            placeholder="请输入密码"
            :disabled="loading"
            autocomplete="current-password"
            prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item class="form-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <a href="#" class="forgot-password">忘记密码？</a>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit" 
            :loading="loading"
            class="login-button"
            size="large"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <p class="login-tip">
          💡 测试账号：<br />
          管理员：admin / admin123<br />
          普通用户：user / user123
        </p>
        <p class="copyright">
          © 2024 Financial Monitoring System. All rights reserved.
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { authAPI } from '../services/api'
import { STORAGE_KEYS } from '../constants'
import { setStorageItem, isEmpty, logger } from '../utils'

const router = useRouter()

const username = ref('')
const password = ref('')
const rememberMe = ref(false)
const error = ref('')
const loading = ref(false)

// 表单验证
const isFormValid = computed(() => {
  return !isEmpty(username.value) && !isEmpty(password.value)
})

// 页面加载时恢复记住的凭据
const restoreCredentials = () => {
  const savedUsername = localStorage.getItem('savedUsername')
  const savedPassword = localStorage.getItem('savedPassword')
  
  if (savedUsername) {
    username.value = savedUsername
    rememberMe.value = true
  }
  
  if (savedPassword) {
    password.value = savedPassword
  }
}

onMounted(() => {
  restoreCredentials()
})

const validateForm = (): boolean => {
  if (isEmpty(username.value)) {
    error.value = '请输入用户名'
    return false
  }
  if (isEmpty(password.value)) {
    error.value = '请输入密码'
    return false
  }
  if (password.value.length < 6) {
    error.value = '密码长度不能少于6位'
    return false
  }
  return true
}

const handleSubmit = async () => {
  error.value = ''

  // 验证输入
  if (!validateForm()) {
    return
  }

  loading.value = true
  logger.info('用户尝试登录', { username: username.value })

  try {
    // 调用登录API
    const response = await authAPI.login(username.value, password.value)
    logger.info('用户登录结果', response)
    
    if (response.success && response.data) {
      logger.info('用户登录成功', { username: username.value })
      // 保存token和用户信息
      setStorageItem(STORAGE_KEYS.AUTH_TOKEN, response.data.token)
      setStorageItem(STORAGE_KEYS.USERNAME, response.data.user.username)
      setStorageItem(STORAGE_KEYS.USER_INFO, response.data.user)
      
      // 如果选择了记住我，保存凭据
      if (rememberMe.value) {
        localStorage.setItem('savedUsername', username.value)
        localStorage.setItem('savedPassword', password.value)
      } else {
        // 否则清除保存的凭据
        localStorage.removeItem('savedUsername')
        localStorage.removeItem('savedPassword')
      }
      
      // 跳转到主页
      router.push('/machines')
    } else {
      logger.warn('登录失败', { response: response })
      logger.warn('登录失败', { username: username.value, message: response.message })
      error.value = response.message || '登录失败'
    }
  } catch (err: any) {
    logger.error('登录过程中发生错误', { username: username.value, error: err.message || err })
    error.value = err.message || '用户名或密码错误'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
@import './Login.css';
</style>